#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <cstring>
#include <memory>
#include <pthread.h>
#include <sys/wait.h>
#include "Logger.hpp"
#include "Common.hpp"
#include "ThreadPool.hpp"
#include <functional>
#include "Protocol.hpp"
#include "Caculate.hpp"
#include "Inet_host.hpp"

using namespace LogMudule;
using namespace ThreadPoolMudule;
const u_int16_t defport = 8888;
const int backlog = 8;
const int deffd = -1;

using hander_t = std::function<std::string(std::string &)>;


class TcpSever
{

private:
    using task_t = std::function<void()>;
    struct ThreadData
    {
        int sockfd;
        TcpSever *self;
    };

    void HanderTask(int sockfd)
    {
        while (true)
        {

            // 读取信息
            char inbuffer[1024];
            std::string package;
            // memset(inbuffer, 0, sizeof(inbuffer));??
            int n = ::recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                LOG(LogLevel::INFO) << "client# " << inbuffer << "  " << sockfd;
                // 写入信息
                inbuffer[n] = 0;
                package += inbuffer;
                std::string result = _hander(package);
                if (result.empty())
                {
                    continue;
                }
                ::send(sockfd, result.c_str(), result.size(), 0);
            }
            else if (n == 0)
            {
                LOG(LogLevel::INFO) << "client close!";
                close(sockfd);
                break;
            }
            else
            {
                LOG(LogLevel::ERROR) << "read error!";
                close(sockfd);
                break;
            }
        }
    }

public:
    TcpSever(hander_t hander, u_int16_t port = defport)
        : _hander(hander),
          _port(port),
          _isrunning(false),
          _listensockfd(deffd)
    {
    }
    void SeverInit()
    {
        // 创建套接字
        _listensockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket 创建失败!";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket 创建成功!";

        // 填充本地信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        // 绑定
        int n = ::bind(_listensockfd, Conv(&local), sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind 失败!";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind 成功!";

        // 监听,获取连接，返回文件描述符
        n = listen(_listensockfd, backlog);
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "listen 失败!";
            exit(3);
        }
        LOG(LogLevel::INFO) << "listen 成功!";
    }

    void Start()
    {
        _isrunning = true;
        while (true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            // 接收信息
            int sockfd = accept(_listensockfd, Conv(&peer), &len);
            if (sockfd < 0)
            {
                LOG(LogLevel::ERROR) << "accept error!";
                continue;
            }
            LOG(LogLevel::INFO) << "accept success!";
            //进程池处理任务
            ThreadPool<task_t>::getInstance()->Equeue([this, sockfd]() {
                this->HanderTask(sockfd);
            });
        }
    }

private:
    int _listensockfd;
    bool _isrunning;
    u_int16_t _port;
    hander_t _hander;
};